<template>
  <view class="proc-wrap">
    <!--    <cu-custom bgColor="bg-blue" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">流程详情</block>
    </cu-custom> -->
    <scroll-view scroll-x class="bg-white nav ">
      <view class="flex text-center">
        <view class="cu-item flex-sub" :class="index == TabCur ? 'text-orange cur' : ''"
          v-for="(item, index) in tabList" :key="index" @tap="tabSelect" :data-id="index">
          {{ item.label }}
        </view>
      </view>
    </scroll-view>
    <view class="detail-view content-box" v-if="TabCur === 0">
      <view class="detail-form" v-if="firstStepInfo&&firstStepInfo.biz_cfg">
        <u-tabs :list="firstStepInfo.biz_cfg" @change="changeMainTab" :is-scroll="true" :current="mainTabCur"></u-tabs>
        <view class="" v-for="(item,mainIndex) in firstStepInfo.biz_cfg">
          <bxform ref="bxDetailForm" :pageType="'detail'" :defaultValue="item.defaultValue" :BxformType="'detail'"
            :fields="item.fields" v-show="mainIndex===mainTabCur"></bxform>
        </view>
      </view>
    </view>
    <view class="steps-view content-box" v-if="TabCur === 1">
      <BxSteps :infoList="procBasicConfig.proCharData" :scroll="scroll" @clickSteps="clickSteps"></BxSteps>
    </view>

    <view class="step-list content-box" v-else-if="TabCur === 2">
      <view class="step-list-item" v-for="(item, index) in procRecord" :key="index" @click="toRecordDetail(item)">
        <view class="title">
          <text class="label">步骤名称：</text>
          <text class="value">{{ item.step_no_name }}</text>
        </view>
        <view class="status">
          <text class="label">处理结果：</text>
          <text class="value">{{ item.proc_result }}</text>
        </view>
        <view class="detail">
          <view class="detail-item">
            <view class="label" v-if="item.data_status">数据状态：{{ item.data_status }}</view>
            <view class="value"></view>
          </view>
          <view class="detail-item">
            <view class="label" v-if="item.create_user">审核人：{{ item.create_user }}</view>
            <view class="value"></view>
          </view>
          <view class="detail-item">
            <view class="label" v-if="item.create_user">创建人：{{ item.create_user }}</view>
            <view class="value"></view>
          </view>

          <view class="detail-item">
            <view class="label">审核时间：{{ item.modify_time.slice(0, 10) }}</view>
            <view class="value"></view>
          </view>
        </view>
      </view>
    </view>

    <view class="bottom-bar">
      <view class="" style="flex: 1;">
        <view class="">
          <text class="text-gray">{{ currentStepInfo.state === '已处理' ? '当前状态：' : '当前步骤：' }}</text>
          <text
            class="value text-blue">{{ currentStepInfo.state === '已处理' ? currentStepInfo.state : currentStepInfo.step_name }}</text>
        </view>
        <view class="">
          <text class="text-gray">处理人：</text>
          <text>{{ currentStepInfo._approval_user ? currentStepInfo._approval_user : currentStepInfo._approval_user_no }}</text>
        </view>
      </view>
      <view class="" v-if="procBasicConfig.proHanleData && procBasicConfig.proHanleData.authority">
        <text class="cu-btn bg-blue margin-right"
          v-if="procBasicConfig.proHanleData && procBasicConfig.proHanleData.activeStep !== 0"
          @click="showApprovalForm(currentStepInfo, 'approval')">
          <!-- 审批 -->
          <!-- {{ currentStepInfo.step_name }} -->
          处理
        </text>
        <text class="cu-btn bg-blue margin-right"
          v-if="procBasicConfig.proHanleData && procBasicConfig.proHanleData.activeStep === 0"
          @click="showApprovalForm(currentStepInfo, 'approval')">
          <!-- 申请 -->
          {{ currentStepInfo.step_name }}
        </text>
      </view>
    </view>
    <uni-popup ref="approvalPopup" type="center">
      <view class="form-view" v-if="stepsCfgData.length > 0">
        <view class="form-box-wrapper">
          <view class="form-box" style="width: 100%;" v-for="(item, index) in stepsCfgData" :key="index">
            <bx-table v-if="item.type==='grid'" :tableName="item._section_name" :serviceName="item.select_service"
              :use_type="item['_type_grid'] == 'readGrid' ? 'procdetaillist' : 'prochandlelist'"
              :table-type="activityData.proc_status==='完成'?'detail':'list'" :condition="item.childCondition"
              :ref="'bxFormStep' + index">
              <template v-slot:title>
                <view class="table-name bg-white padding-tb-sm  text-blue">
                  <text>{{item._section_name||''}}</text>
                </view>
              </template>
            </bx-table>
            <bxform style="width: 100%;" :ref="'bxFormStep' + index" :pageType="item.formType"
              :BxformType="item.formType" :fields="item.fields" v-else>
              <view class="child-service" v-if="item.child_service&&item.child_service.length>0">
                <child-form v-for="form in item.child_service" :defaultVal="item.defaultVal" :form-cfg="form">
                </child-form>
              </view>
            </bxform>
          </view>
        </view>

        <bxform style="width: 100%;" v-if="isHandler" ref="approvalForm" :pageType="'detail'" :BxformType="'detail'"
          :fields="approvalFormCfg"></bxform>
        <bxform style="width: 100%;"
          v-if="procBasicConfig.proHanleData && procBasicConfig.proHanleData.activeStep !== 0 && !isHandler"
          ref="approvalForm" :pageType="'add'" :BxformType="'add'" :fields="approvalFormCfg"></bxform>
        <view class="button-box"
          v-if="procBasicConfig.proHanleData && procBasicConfig.proHanleData.activeStep !== 0 && !isHandler">
          <text class="cu-btn bg-blue margin-right" @click="approvalForm">提交</text>
          <text class="cu-btn bg-green" @click="$refs.approvalPopup.close()">取消</text>
        </view>
        <text class="cu-btn bg-blue" @click="$refs.approvalPopup.close()" v-if="isHandler">确定</text>
      </view>
    </uni-popup>

    <uni-popup ref="recordPopup" type="bottom">
      <view class="form-view" v-if="currentRecord.fields && currentRecord.fields.length > 0">
        <bxform ref="bxFormRecord " pageType="detail" BxformType="detail" :fields="currentRecord.fields"></bxform>
        <view class="cu-btn bg-blue radius" @click="$refs.recordPopup.close()">确定</view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import bxform from '@/components/bx-form/bx-form.vue';
  import childForm from './child-form.vue'
  import uniPopup from '@/components/uni-popup/uni-popup.vue';
  import BxSteps from '@/components/bx-steps/bx-steps.vue';

  const approvalFormCfgInit = [{
      label: '意见',
      column: 'proc_result',
      value: '',
      type: 'radioFk',
      display: true,
      isRequire: true,
      isShowExp: [],
      options: [{
          value: 'pass',
          label: '已处理'
        },
        {
          value: 'turn',
          label: '转派'
        },
        {
          value: 'return_to_start',
          label: '退回开始'
        },
        {
          value: 'return_to_last',
          label: '退回'
        }
      ]
    },
    {
      label: '转派用户',
      column: 'turn_user_no',
      value: '',
      srvInfo: {
        serviceName: 'srvsso_user_select',
        appNo: 'sso',
        isTree: false,
        column: 'user_no',
        showCol: 'real_name', //要展示的字段
        srv_app: 'sso'
      },
      option_list_v2: {
        refed_col: 'user_no',
        srv_app: 'sso',
        serviceName: 'srvsso_user_select',
        conditions: [{
          colName: 'dept_no',
          ruleType: 'eq',
          value: 'bx100sys'
        }],
        key_disp_col: 'user_disp'
      },
      type: 'treeSelector',
      display: true,
      disabled: false,
      isRequire: true,
      isShowExp: [{
        colName: 'proc_result',
        ruleType: 'eq',
        value: 'turn'
      }],
      options: []
    },
    {
      label: '说明',
      column: 'remark',
      value: '',
      type: 'textarea',
      display: true,
      isRequire: false,
      isShowExp: [{
        colName: 'proc_result',
        ruleType: 'eq',
        value: 'pass'
      }],
      options: []
    },
    {
      label: '说明',
      column: 'remark',
      value: '',
      type: 'textarea',
      display: true,
      isRequire: false,
      isShowExp: [{
        colName: 'proc_result',
        ruleType: 'eq',
        value: 'consent'
      }],
      options: []
    },
    {
      label: '说明',
      column: 'remark',
      value: '',
      type: 'textarea',
      display: true,
      isRequire: true,
      isShowExp: [{
          colName: 'proc_result',
          ruleType: 'neq',
          value: ''
        },
        {
          colName: 'proc_result',
          ruleType: 'neq',
          value: 'pass'
        },
        {
          colName: 'proc_result',
          ruleType: 'neq',
          value: 'consent'
        }
      ],
      options: []
    }
  ]
  export default {
    components: {
      bxform,
      childForm,
      uniPopup,
      BxSteps
    },
    computed: {
      appName() {
        return uni.getStorageSync('activeApp')
      }
    },
    data() {
      return {
        modalName: "",
        mainTabCur: 0,
        TabCur: 1,
        scrollLeft: 0,
        tabList: [{
            label: '基本信息'
          },
          {
            label: '流程步骤'
          },
          {
            label: '审批结果'
          }
        ],
        isHandler: false,
        activityData: {},
        proc_instance_no: '',
        scroll: 0,
        type: 'add',
        procRecord: [],
        recordFields: [],
        currentRecord: {},
        procBasicConfig: {},
        colsV2Data: {},
        srvInfo: {
          app: '',
          serviceName: 'srvprocess_basic_cfg_select'
        },
        currentStepInfo: {}, //当前步骤的信息
        stepsCfgData: [], //当前步骤表单数据
        firstStepInfo: {}, //基础信息
        firstStepForm: [],
        formInfo: {
          serviceName: '',
          formType: ''
        },
        showProcApproval: false, //是否显示审批表单
        approvalVal: {
          proc_result: '',
          remark: '',
          turn_user_no: '',
          step_no: ''
        },
        fields: [],
        currentStepFields: [], //当前步骤的字段
        authority: false, //编辑权限
        approvalFormCfg: []
      };
    },
    methods: {
      hideModal() {
        this.modalName = ''
      },
      showModal(e) {
        this.modalName = e
      },
      changeMainTab(index) {
        this.mainTabCur = index
      },
      tabSelect(e) {
        this.TabCur = Number(e.currentTarget.dataset.id);
        this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
      },
      toRecordDetail(data) {
        //查看流程审批记录详情
        console.log(data);
        this.currentRecord = data;
        this.$refs.recordPopup.open();
      },
      hideApprovalForm() {
        this.$refs.approvalPopup.close();
      },
      async getDefaultVal(e, condition) {
        let app = this.appName || uni.getStorageSync('activeApp');
        let url = this.getServiceUrl(app, e.select_service, 'select');
        let req = {
          serviceName: e.select_service,
          colNames: ['*'],
          condition: condition,
          page: {
            pageNo: 1,
            rownumber: 10
          }
        };
        let res = await this.$http.post(url, req);
        if (res.data.state === 'SUCCESS') {
          if (Array.isArray(res.data.data) && res.data.data.length > 0) {
            return res.data.data[0];
          }
        }

      },
      showApprovalForm(data, type) {
        this.stepsCfgData = [];
        if (data.state === '已处理') {
          this.isHandler = true;
        } else {
          this.isHandler = false;
        }
        this.getApprovalForm(data).then(e => {
          if (e) {
            this.stepsCfgData = [];
            let fieldList = this.deepClone(e);
            if (fieldList.length > 0) {
              fieldList.forEach(item => {

                if (item.biz_type === "main") {
                  item.childCondition = [{
                    colName: "proc_instance_no",
                    ruleType: "eq",
                    value: item.proc_instance_no
                  }]
                } else if (item.biz_type) {
                  item.childCondition = [{
                    colName: "parent_proc_instance_no",
                    ruleType: "eq",
                    value: item.proc_instance_no
                  }]
                }
              })
            }
            console.log(this.approvalFormCfg)
            if (type && type == 'approval') {

              if (data?.approval_options) {
                if (Array.isArray(data.approval_options) && data.approval_options.length ===
                  1) {
                  this.approvalFormCfg[0].value = 'consent'
                  this.approvalFormCfg[0].display = false
                }
                let approval_options = this.deepClone(data.approval_options)
                this.approvalFormCfg[0].options = approval_options.map(item => {
                  item.label = item.disp
                  const key = item.key
                  const key_value = item["value"];
                  if (key == undefined) {
                    item["key_value"] = key_value;
                    item["key"] = key_value;
                  } else {
                    item["key_value"] = key_value;
                    item["value"] = key;
                  }
                  return item
                })
              }

              this.approvalFormCfg.forEach(item => {
                if (item.options?.length === 1) {

                } else {
                  item.value = '';
                }
              });
              if (fieldList.length > 0) {
                fieldList.forEach(item => {
                  if (item.type === 'grid' && item._type_grid === 'editGrid') {
                    item.childCondition = [{
                      colName: "parent_proc_instance_no",
                      ruleType: "eq",
                      value: item.proc_instance_no
                    }]
                  } else if (item.type === 'form' && item._type_form === 'update') {
                    let condition = [{
                      colName: "parent_proc_instance_no",
                      ruleType: "eq",
                      value: item.proc_instance_no
                    }]
                    if (item.biz_type === "main") {
                      item.childCondition = [{
                        colName: "proc_instance_no",
                        ruleType: "eq",
                        value: item.proc_instance_no
                      }]
                    } else if (item.biz_type == "child") {
                      item.childCondition = [{
                        colName: "parent_proc_instance_no",
                        ruleType: "eq",
                        value: item.proc_instance_no
                      }]
                    }
                    if (item.fields) {
                      this.getDefaultVal(item, item.childCondition).then(res => {
                        if (res) {
                          item.fields = this.setFieldsDefaultVal(item.fields, res)
                          item.defaultValue = res
                        }
                      })
                    }
                  }
                  if (item.fields) {
                    item.fields.forEach(item2 => {
                      item2.value = item2.value || '';
                    });
                  }
                });
              }
            }
            this.stepsCfgData = fieldList;
            this.$refs.approvalPopup.open();
            // this.showModal('approvalPopupModalName')
          }
        });
      },
      clickSteps(e) {
        console.log(this.deepClone(e))
        if (e.data.step_no === this.currentStepInfo.step_no && !this.procBasicConfig.proHanleData.authority && e.data
          .state !== '已处理') {
          //若 点击的步骤是当前处理步骤并且当前登录用户没有权限操作
          uni.showToast({
            title: '无权处理',
            icon: 'none'
          });
          return;
        }
        this.approvalFormCfg = this.deepClone(approvalFormCfgInit)
        console.log(this.approvalFormCfg)
        let approvalFormCfg = this.approvalFormCfg;
        let stepData = e.data;
        let recordData = this.procRecord;
        recordData.forEach(record => {
          if (stepData.step_no === record.step_no) {
            stepData.remark = record.remark;
            stepData.proc_result = record.proc_result;
            console.log('step,record', stepData);
            Object.keys(stepData).forEach(key => {
              this.approvalFormCfg.forEach((field, index) => {
                if (field.column === key) {
                  field['value'] = stepData[key];
                  this.$set(this.approvalFormCfg, index, field);
                }
              });
            });
          }
        });
        if (e.index !== 0 && e.index <= this.scroll) {
          if (e.data.state !== '已处理') {
            this.showApprovalForm(e.data, 'approval');
          } else {
            this.showApprovalForm(e.data);
          }
        } else if (e.index === 0) {
          this.TabCur = 0;
        }
        console.log('clickSteps', e);
        // }
      },
      async getBasicCfg(proc_instance_no) {
        // srvprocess_basic_cfg_select 流程初始化数据查询
        let serviceName = this.srvInfo.serviceName;
        let req = {
          serviceName: 'srvprocess_basic_cfg_select',
          colNames: ['*'],
          condition: [{
            colName: 'proc_instance_no',
            ruleType: 'eq',
            value: proc_instance_no
          }]
        };
        let res = await this.onRequest('select', 'srvprocess_basic_cfg_select', req, this.appName);
        if (res.data.state === 'SUCCESS') {
          this.procBasicConfig = res.data;

          if (res.data.proHanleData?.activeStep === 0) {
            if (res.data?.proHanleData?.authority === true) {
              uni.showModal({
                title: '请前往PC页面操作提交申请',
                showCancel: false,
                success() {
                  uni.navigateBack({
                    delta: 1
                  })
                }
              })
            } else {
              uni.showModal({
                title: '无权处理',
                showCancel: false,
                success() {
                  uni.reLaunch({
                    url: '/pages/specific/index/index'
                  })
                  // uni.navigateBack({
                  //   delta: 1
                  // })
                }
              })
              // uni.navigateBack({
              //   delta: 1
              // })
            }
            return
          }
          this.activityData = res.data.mainData;
          if (res.data?.proc_basic?.proc_name) {
            uni.setNavigationBarTitle({
              title: res.data?.proc_basic?.proc_name
            })
          }
          // this.getCurStepConfig(res.data['proCharData'][res.data['proHanleData']['activeStep']]);
          this.getApprovalForm(res.data['proCharData'][res.data['proHanleData']['activeStep']]); //获取当前步骤的信息
          this.firstStepInfo = await this.getFirstStepConfig(res.data['proCharData'][0], 'firstStep'); //获取第一步信息

          this.currentStepInfo = res.data['proCharData'][res.data['proHanleData']['activeStep']];
          if (Array.isArray(this.currentStepInfo?.biz_cfg_data) && this.currentStepInfo?.biz_cfg_data.length > 0) {
            if (Array.isArray(this.firstStepInfo?.biz_cfg_data) && this.firstStepInfo?.biz_cfg_data.length > 0) {
              this.currentStepInfo.biz_cfg_data = this.currentStepInfo?.biz_cfg_data.map(item => {
                this.firstStepInfo?.biz_cfg_data.forEach(item1 => {
                  if (item1?.select_service && item1?.select_service === item.select_service) {
                    if (Array.isArray(item1?.colV2?.child_service) && item1?.colV2?.child_service.length >
                      0) {
                      item.child_service = item1?.colV2?.child_service
                      item.defaultVal = item1?.defaultVal
                      this.getColV2(item.select_service, 'detail', true).then(colv2 => {

                      })
                    }
                  }
                })
                return item
              })
            }
          }
          // this.firstStepInfo = res.data['proCharData'][0];

          this.scroll = res.data.proHanleData.activeStep;
        }
      },
      async getApprovalForm(e) {
        let cfg = e.biz_cfg_data; //表单配置
        let cfgData = [{
          type: '',
          serviceName: '',
          fields: [],
          formData: {}
        }];
        if (cfg && cfg.length > 0) {
          for (let i = 0; i < cfg.length; i++) {
            const item = cfg[i];
            if (item.type === 'form') {
              if (item._type_form && e.state !== '已处理') {
                let serviceName = item[`${item._type_form}_service`];
                let type = item._type_form;
                // let fields = await this.getServiceV2(serviceName, item._type_form, item._type_form);
                let fields = await this.getColV2(serviceName, item._type_form);
                cfg[i]['fields'] = fields.filter(item => {
                  return item.col_type !== "FileList" && !["expense_item_file", "cost_calc_file"].includes(item
                    .column)
                });
                debugger
                cfg[i]['formType'] = type;
              } else if (item.select_service && e.state === '已处理' && item._type_form) {
                let serviceName = item.select_service;
                let fields = await this.getColV2(serviceName, 'detail');
                cfg[i]['formType'] = 'detail';
                debugger
                let data = await this.getDetail(serviceName, fields, item.biz_type);
                console.log('getDetail(serviceName)', data);
                if (typeof data === 'object') {
                  Object.keys(data).forEach(key => {
                    fields.forEach((field, index) => {
                      if (field.column === key) {
                        field['value'] = data[key];
                        field['disabled'] = true;
                        this.$set(fields, index, field);
                        cfg[i]['fields'] = fields;
                      }
                    });
                  });
                }
              } else if (e.step_no) {
                // let fields = [{
                //   "label": "意见",
                //   "column": "proc_result",
                //   "value": e.proc_result,
                //   "type": "input",
                //   "display": true,
                //   "isRequire": false,
                //   "isShowExp": [],
                // }, {
                //   "label": "说明",
                //   "column": "remark",
                //   "value":e.remark,
                //   "type": "textarea",
                //   "display": true,
                //   "isRequire": false,
                //   "isShowExp": [],
                // }]
                // cfg[i]['fields'] = fields;
                // cfg[i]['formType'] = 'detail';
              }
            }
          }
          return cfg;
        } else {
          debugger
          return this.approvalFormCfg;
        }
      },
      async getProcRecord() {
        //查找流程审批记录
        let serviceName = 'srvprocess_record_select'
        serviceName = 'srvprocess_result_select'
        let req = {
          serviceName: serviceName,
          colNames: ['*'],
          condition: [{
            colName: 'proc_instance_no',
            value: this.proc_instance_no,
            ruleType: 'eq'
          }],
          order: [{
            colName: 'id',
            orderType: 'desc'
          }]
        };
        let res = await this.onRequest('select', serviceName, req, this.appName);
        if (res.data.state === 'SUCCESS') {
          this.procRecord = res.data.data;
          this.getColV2(req.serviceName, 'detail').then(cols => {
            debugger
            console.log('recordFields', cols);
            this.recordFields = cols;
            this.procRecord.forEach((item, i) => {
              let recordFields = this.deepClone(cols);
              console.log('recordFields121', item);
              Object.keys(item).forEach(key => {
                recordFields.forEach((field, index) => {
                  if (field.column === key) {
                    field['value'] = item[key];
                  }
                });
              });
              item['fields'] = recordFields;
              this.$set(this.procRecord, i, item);
            });
          });
        }
      },
      async getDetail(serviceName, fields, biz_type) {
        uni.showLoading({});
        let col = fields.map(item => item.column);
        let req = {
          serviceName: serviceName,
          condition: [{
            colName: biz_type == 'main' ? 'proc_instance_no' : 'parent_proc_instance_no',
            // colName: 'proc_instance_no',
            ruleType: 'eq',
            value: this.proc_instance_no
          }],
          colNames: col,
          hisVer: true
        };
        let res = await this.onRequest('select', req.serviceName, req, this.appName);
        uni.hideLoading();
        if (res.data.state === 'SUCCESS') {
          if (res.data.data.length > 0) {
            return res.data.data[0];
          }
        }
      },
      async getFirstStepConfig(e) {
        if (e && e.state !== '未开始') {
          if (e.biz_cfg_data && e.biz_cfg_data.length > 0) {
            const biz_cfg = e.biz_cfg_data;
            for (let item of biz_cfg) {

              let colV2 = await this.getColV2(item.select_service, 'detail', true)
              if (colV2?.colVs?.service_view_name) {
                item.colV2 = colV2.colVs
                item.name = colV2.colVs.service_view_name.replace('查询', '').replace('列表', '')
                if (item.biz_type === 'main') {
                  item.name = '项目基本信息'
                  item.defaultValue = this.activityData
                }
              }
              if (colV2?.fields) {
                let condition = []
                if (item.biz_type === 'main') {
                  condition = [{
                    colName: "proc_instance_no",
                    ruleType: "eq",
                    value: item.proc_instance_no
                  }]
                } else if (item.biz_type === 'child') {
                  condition = [{
                    colName: "parent_proc_instance_no",
                    ruleType: "eq",
                    value: item.proc_instance_no
                  }]
                }
                let defaultVal = await this.getDefaultVal(item, condition)
                item.defaultVal = defaultVal
                item.fields = this.setFieldsDefaultVal(colV2?.fields, defaultVal)
              }
            }
            // biz_cfg.forEach(async (item) => {
            //   let colV2 = await this.getColV2(item.select_service, 'detail', true)
            //   if (colV2?.colVs?.service_view_name) {
            //     item.colV2 = colV2.colVs
            //     item.name = colV2.colVs.service_view_name.replace('查询', '').replace('列表', '')
            //     if (item.biz_type === 'main') {
            //       item.name = '项目基本信息'
            //       item.defaultValue = this.activityData
            //     }
            //   }
            //   if (colV2?.fields) {
            //     let condition = []
            //     if (item.biz_type === 'main') {
            //       condition = [{
            //         colName: "proc_instance_no",
            //         ruleType: "eq",
            //         value: item.proc_instance_no
            //       }]
            //     } else if (item.biz_type === 'child') {
            //       condition = [{
            //         colName: "parent_proc_instance_no",
            //         ruleType: "eq",
            //         value: item.proc_instance_no
            //       }]
            //     }
            //     let defaultVal = await this.getDefaultVal(item, condition)
            //     item.fields = this.setFieldsDefaultVal(colV2?.fields, defaultVal)
            //   }
            // })
            e.biz_cfg = biz_cfg
          }
        }
        return e
      },
      getCurStepConfig(e, type) {
        if (e && e.state !== '未开始') {
          console.log('getCurStepConfig', e);
          if (e.biz_cfg_data && e.biz_cfg_data.length > 0) {
            const biz_cfg = e.biz_cfg_data;
            biz_cfg.map(item => {
              if (item._type_form) {
                if (type === 'firstStep') {
                  item._type_form = 'detail'
                  item.detail_service = item.select_service
                }
                this.formInfo.formType = item._type_form;
                this.type = item._type_form;
                this.formInfo.serviceName = item[`${item._type_form}_service`];
                this.getColV2(item[`${item._type_form}_service`], item._type_form).then(fields => {
                  if (type === 'firstStep') {
                    this.fields = fields;
                    item.fields = fields
                    this.getDefaultVal(item).then(res => {
                      if (res) {
                        item.fields = this.setFieldsDefaultVal(item.fields, res)
                        item.defaultValue = res
                      }
                    })
                    // Object.keys(this.procBasicConfig.mainData).forEach(key => {
                    //   this.fields.forEach((field, index) => {
                    //     if (field.column === key) {
                    //       field['value'] = this.procBasicConfig.mainData[key];

                    //       this.$set(this.fields, index, field);
                    //     }
                    //   });
                    // });
                  } else {
                    this.currentStepFields = fields;
                  }
                });
              } else if (item.select_service) {
                this.formInfo.formType = 'detail';
                this.type = 'detail';
                this.formInfo.serviceName = item.select_service;
                this.getColV2(item.select_service, 'detail').then(fields => {
                  if (type === 'firstStep' && item.biz_type == 'main') {
                    // this.fields = fields;
                    // Object.keys(this.procBasicConfig.mainData).forEach(key => {
                    //   this.fields.forEach((field, index) => {
                    //     if (field.column === key) {
                    //       field['value'] = this.procBasicConfig.mainData[key];
                    //       this.$set(this.fields, index, field);
                    //     }
                    //   });
                    // });
                  } else {
                    this.currentStepFields = fields;
                  }
                });
              }
            });
          }
        }
      },
      async approvalForm() {
        // 提交审批
        let self = this;
        debugger
        if (this.procBasicConfig.proHanleData.activeStep === 0) {
          //重新申请
          for (let i = 0; i < this.stepsCfgData.length; i++) {
            let ref = 'bxFormStep' + i;
            let item = this.stepsCfgData[i];
            if (item.formType) {
              let serviceName = item[`${item.formType}_service`];
              let itemData = self.$refs[ref][0].getFieldModel();
              // if (!itemData) {
              // 	itemData = this.activityData;
              // }
              if (!itemData.file_no) {
                itemData.file_no = '';
              }
              if (!itemData.remark) {
                itemData.remark = '';
              }
              if (itemData === false) {
                return;
              }
              let req = [{
                serviceName: 'srvoa_issue_info_update',
                condition: [{
                  colName: 'proc_instance_no',
                  ruleType: 'eq',
                  value: this.proc_instance_no
                }],
                proc_instance_no: this.proc_instance_no,
                data: [itemData]
              }];
              let res = await this.onRequest('apply', serviceName, req, this.appName);
              if (res.data.state === 'SUCCESS') {
                console.log(res.data, 'res.data');
                uni.showToast({
                  title: res.data.resultMessage,
                  icon: 'none'
                });
                uni.showModal({
                  title: '提示',
                  content: res.data.resultMessage,
                  showCancel: false,
                  success(res) {
                    if (res.confirm) {
                      self.hideApprovalForm();
                      self.getBasicCfg(self.proc_instance_no);
                      self.getProcRecord(self.proc_instance_no);
                      uni.$emit('procSubmit', true)
                    }
                  }
                });
              } else {
                uni.showToast({
                  title: res.data.resultMessage,
                  icon: 'none'
                });
              }
              // });
            }
          }
        } else {
          let approval = {}

          // if (Array.isArray(this.currentStepInfo.approval_options) && this.currentStepInfo.approval_options.length ===
          //   1) {
          //   approval.proc_result = this.currentStepInfo.approval_options[0]['key'] || this.currentStepInfo
          //     .approval_options[0]['value']
          // } else {
          approval = self.$refs.approvalForm.getFieldModel();
          // }
          debugger
          console.log('approval', approval);
          // let option = 
          let child_data_list = [];
          let id = this.procBasicConfig.mainData.id;
          let stepsCfgData = this.stepsCfgData;
          let proc_result = ''
          let result_key = ''
          let approval_options = this.currentStepInfo.approval_options
          if (Array.isArray(approval_options) && approval_options.length > 0) {
            approval_options.forEach(item_result => {
              if (item_result["value"] == approval.proc_result || item_result["key"] == approval.proc_result) {
                proc_result = item_result["key_value"] || item_result["value"];
                result_key = item_result["key"];
              }
            })
          }


          // for (let item_result of this.currentStepInfo.approval_options) {
          //   if (item_result["value"] == approval.proc_result) {
          //     proc_result = item_result["key_value"];
          //     result_key = item_result["key"];
          //   }
          // }


          if (proc_result === 'pass') {
            for (let index = 0; index < this.stepsCfgData.length; index++) {
              let refName = `bxFormStep${index}`
              let childData = self.$refs[refName][0].getFieldModel()
              let itemCfg = self.stepsCfgData[index];
              if (itemCfg._type_grid === "editGrid") {
                let list = childData?.list
                if (Array.isArray(list) && list.length > 0) {
                  list.forEach(data => {
                    let result = {}
                    Object.keys(data).forEach(key => {
                      if (key.indexOf('_') !== 0) {
                        result[key] = data[key]
                      }
                    })
                    let obj = {
                      serviceName: itemCfg.update_service,
                      data: [result],
                      condition: [{
                        colName: 'id',
                        ruleType: 'in',
                        value: data.id
                      }]
                    };
                    child_data_list.push(obj);
                  })
                }
              } else if (itemCfg.formType) {
                if (itemCfg.defaultValue && Object.keys(itemCfg.defaultValue).length > 0 && typeof childData ===
                  "object" && Object.keys(childData).length > 0) {
                  Object.keys(itemCfg.defaultValue).forEach(key => {
                    Object.keys(childData).forEach(key2 => {
                      if (itemCfg.defaultValue[key] && key == 'id' && key.indexOf(
                          '_') !== 0 && key !== key2) {
                        childData[key] = itemCfg.defaultValue[key]
                      }
                    })
                  })
                }
                let serviceName = itemCfg[`${itemCfg.formType}_service`];
                let obj = {
                  serviceName: itemCfg[`${itemCfg.formType}_service`],
                  data: [childData],
                  condition: [{
                    colName: 'id',
                    ruleType: 'eq',
                    value: childData?.id
                  }]
                };
                if (childData?.id) {
                  child_data_list.push(obj);
                }
              }
            }
          }
          console.log(child_data_list, 'child_data_list');

          let reqData = [{
            data: [{
              child_data_list: child_data_list,
              proc_result: proc_result,
              key: result_key,
              remark: approval.remark,
              turn_user_no: approval.turn_user_no
            }],
            proc_instance_no: self.proc_instance_no,
            step_no: self.currentStepInfo.step_no
          }];
          let url = this.getServiceUrl(this.appName, 'approval', 'process');
          let res = await self.onRequest('process', 'approval', reqData, this.appName);
          // .then(res => {
          if (res.data.state === 'SUCCESS') {
            console.log(res.data);
            uni.showToast({
              title: res.data.resultMessage,
              icon: 'none'
            });
            uni.showModal({
              title: '提示',
              content: res.data.resultMessage,
              showCancel: false,
              success: (res) => {
                if (res.confirm) {
                  window.location.reload()
                }
              }
            })
            this.hideApprovalForm();
            uni.$emit('procSubmit', true)
            // this.getBasicCfg(this.proc_instance_no);
            // this.getProcRecord(this.proc_instance_no);
          } else {
            uni.showModal({
              title: '提示',
              content: res.data.resultMessage,
              showCancel: false
            })
          }
          // });
          console.log(`reqData`, reqData);
        }
      },
      async getColV2(serviceName, type, all) {
        let colVs = await this.getServiceV2(serviceName, type, type, this.appName);
        this.colsV2Data = colVs;
        // let type = this.type;
        console.log('colsV2Data', colVs);
        let fields = [];
        switch (type) {
          // case 'update':
          //   fields = this.setFieldsDefaultVal(colVs._fieldInfo, this.activityData);
          //   break;
          case 'update':
            fields = colVs._fieldInfo;
            break;
          case 'add':
            fields = colVs._fieldInfo;
            break;
          case 'detail':
          case 'procdetail':
            fields = this.setFieldsDefaultVal(colVs._fieldInfo, this.activityData);
            break;
          default:
            break;
        }
        if (this.scroll === 0 && type == 'update') {
          fields = this.setFieldsDefaultVal(colVs._fieldInfo, this.activityData);
        }
        if (fields && Array.isArray(fields)) {
          fields = fields.filter((item, index) => {
            if (!item.value) {
              item.value = '';
            }
            // if (item.type === 'Note') {
            //   item.type = 'textarea';
            // }
            // if (item['in_' + type] === 1) {
            return item;
            // }
          });

          // this.fields = fields;
        }
        if (all === true) {
          return {
            fields: fields,
            colVs: colVs
          }
        }
        console.log('colsV2Datafields', fields);
        return fields;
      }
    },
    onLoad(option) {
      if (option.proc_instance_no) {
        this.proc_instance_no = option.proc_instance_no;
        this.srvInfo.app = uni.getStorageSync('activeApp');
        this.getBasicCfg(option.proc_instance_no);
        this.getProcRecord(option.proc_instance_no);
      }
    }
  };
</script>

<style scoped lang="scss">
  .proc-wrap {
    padding-bottom: 150upx;
    position: relative;

    .nav {
      height: 90upx;
    }

    .scroll-fixed {
      top: 90upx;
      z-index: 1024;
      position: fixed;
    }

    .uni-popup {
      z-index: 999;
    }

    /deep/ .uni-scroll-view {
      height: auto;
    }
  }

  .steps-view {
    // margin-top: 100upx;
    // padding-bottom: 150upx;
  }

  .flow-view {
    width: 100%;
    // min-height: 80vh;
    margin-top: 10upx;
    background-color: #fff;
    overflow: hidden;

    .scroll-view {
      padding: 30upx 10upx;
    }

    .cu-timeline {
      .cu-item {
        padding: 5px 15px 5px 54px;
        position: relative;
        display: block;
        z-index: 0;
      }

      .head {
        display: flex;
      }

      .name {
        flex: 1;
        font-size: 34upx;
        line-height: 60upx;
        font-weight: 700;
      }

      .state {
        flex: 1;
        font-size: 30upx;
        line-height: 60upx;
      }
    }
  }

  .step-list {
    width: 100%;
    display: flex;
    flex-direction: column;

    .step-list-item {
      background-color: #fff;
      width: calc(100% - 20upx);
      display: flex;
      flex-direction: column;
      margin: 10upx;
      padding: 20upx;
      border-radius: 10upx;

      .title {
        font-size: 32upx;
        line-height: 50upx;
        font-weight: bold;
      }

      .detail {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        .detail-item {
          min-width: 40%;
        }
      }
    }
  }

  .detail-view {
    margin-top: 10upx;
    padding-bottom: 150upx;
    min-height: 100vh;
    background-color: #fff;
    display: flex;
    flex-direction: column;
  }

  .cu-dialog {
    height: auto;
  }

  .form-view {
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    max-height: calc(100vh - 200upx);
    padding: 30rpx 0 50rpx;
    overflow: scroll;
    // min-width: 200px;
    width: 90vw;

    .form-box-wrapper {
      width: calc(100% - 30px);
      flex: 1;
      overflow-y: scroll;
    }

    .form-box {
      // padding: 0 10px;

      // border: 1px solid #f1f1f1;
    }

    .button-box {
      height: 100upx;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      // margin: 20upx 0 40upx;
    }

    .cu-btn {
      max-width: 60%;
      min-height: 60upx;
      margin-top: 50upx;
    }
  }

  .bottom-bar {
    background-color: #fff;
    z-index: 20;
    width: 100%;
    min-height: 100upx;
    padding-left: 20upx;
    display: flex;
    // flex-direction: column;
    // justify-content: center;
    align-items: center;
    border-top: 1px solid rgba($color: #999, $alpha: 0.5);
    position: fixed;
    bottom: 0;

    .text-blue {
      font-weight: bold;
      font-size: 32upx;
    }
  }

  .content-box {
    margin-bottom: 100upx;
  }
</style>
